import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

public class client {

	private Socket socket;
	private PrintWriter out;
	private BufferedReader In;
	private String IP_Rasp = "192.168.0.10";
	
	public client(int port) {
		try {
			socket = new Socket(InetAddress.getByName(IP_Rasp), port,
					InetAddress.getLocalHost(), port);
			out = new PrintWriter(socket.getOutputStream());
			In = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String s1 = "add / \n";
			byte[] b = s1.getBytes("UTF8" /* encoding */);
			String s2 = new String(b, "UTF8");
			this.envoyer(s2);
		} catch (Exception e) {
			
				IP_Rasp = JOptionPane.showInputDialog("Entrez l'IP de la raspberry");
				if (IP_Rasp != null)
				{
					try {
						socket = new Socket(InetAddress.getByName(IP_Rasp), port,
								InetAddress.getLocalHost(), port);
						out = new PrintWriter(socket.getOutputStream());
						In = new BufferedReader(new InputStreamReader(
								socket.getInputStream()));
						String s1 = "add / \n";
						byte[] b = s1.getBytes("UTF8" /* encoding */);
						String s2 = new String(b, "UTF8");
						this.envoyer(s2);
					} catch (Exception exp) {
						JOptionPane.showMessageDialog(null,"Erreur lors de la connection à la Raspberry -Verifiez l'adresse IP-");
						System.exit(1);
					}
				}
				else
				{
					JOptionPane.showMessageDialog(null,"Aucune adresse entrée, fermeture ");
					System.exit(3);
				}
		}
	}

	public client() {
		this(6600);
	}

	public void close() {
		try {
			socket.close();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	public void envoyer(String str) {
		out.print(str);
		out.flush();
	}

	public void envoyer(int nb) {
		try {
			String encodingName = "UTF8";
			String s1 = "setvol " + String.valueOf(nb) + "\n";
			byte[] b = s1.getBytes("UTF8" /* encoding */);
			String s2 = new String(b, encodingName);
			this.envoyer(s2);
			// System.out.println(s2);
		} catch (Exception e) {
		}
	}

	public String[] client_reception() {
		String message_distant;
		String infos_chanson[] = new String[2];
		try {
			while (In.ready()) {
				message_distant = In.readLine();
				if (message_distant.contains("Title:")) {
					infos_chanson[0] = message_distant.replace("Title:", "");
				}
				if (message_distant.contains("Artist")) {
					infos_chanson[1] = message_distant.replace("Artist:", "");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return (infos_chanson);
	}

}
